import React, { useState, useEffect, useContext, useReducer, Fragment } from 'react';
import { Link as RouterLink , useNavigate,useLocation, useParams, useRoutes, useMatch } from 'react-router-dom';
import { useFormik, Formik, Form, Field, ErrorMessage } from 'formik';
import PropTypes from 'prop-types';
import _, { filter } from 'lodash';
import { sentenceCase } from 'change-case';
import * as XLSX from 'xlsx';


// material
import {
    Card,
    Table,
    Stack,
    Avatar,
    Button,
    Checkbox,
    IconButton,
    TableRow,
    TableBody,
    TableCell,
    Container,
    Typography,
    TableContainer,
    TablePagination,
    Dialog,
    DialogTitle,
    DialogContent,
    TextField,
    DialogActions,
    Grid,
    CardContent,
    FormControl,
    InputLabel, OutlinedInput, CardActions, MenuItem, Select
} from '@mui/material';

// material-lab
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DatePicker from '@mui/lab/DatePicker';

//icons-eva
import { Icon } from '@iconify/react';
import editFill from '@iconify/icons-eva/edit-fill';
import trash2Outline from "@iconify/icons-eva/trash-2-outline";
import plusFill from '@iconify/icons-eva/plus-fill';

// components
import Page from '../../../components/Page';
import Label from '../../../components/Label';
import Scrollbar from '../../../components/Scrollbar';
import SearchNotFound from '../../../components/SearchNotFound';
//
import USERLIST from '../../../_mocks_/user';

//
import { fetchAjax, postAjax, putAjax, deleteAjax, postUpload } from '../../../request';
import { systemUsersService } from '../../../API/system/system-user.service';

//
import { mockImgAvatar } from '../../../utils/mockImages';


/*=======================================================================================*/

const ProfileContext = React.createContext();

const queryParams = {
    userName: '',
    status: '',
    deptId: ''
}

const initialValues = {
    name: '',
    email: '',
    telephone: '',
    phone: '',
    gender: '',
    avatarUrl: '',
    dob: new Date()
}

function reducer(state, action) {
    switch (action.type) {
        case 'SEARCH_FORM':
            return action.data;
        case 'EDIT_FORM':
            return action.data;
        case 'OPEN_DIALOG':
            return action.data;
        default:
            return initialValues;
    }
}


// ----------------------------------------------------------------------

function EnhancedDetail({ detail }) {

    const { state, dispatch } = useContext(ProfileContext);

    const formik = useFormik({
        initialValues: state?.initialValues || initialValues,
        onSubmit: (values, event) => {
            values.id ? putAjax(`/api/system/user`, values).then(data=>{
                console.log('hello',data)
            }) : postAjax(`/api/system/user`, values).then(data=>{
                console.log('world',data)
            })
        },
    });

    const [previewAvatar, setPreviewAvatar] = useState();

    const [previewText, setPreviewText] = useState();

    const [previewExcel, setPreviewExcel] = useState();

    const handleEdit = (record)=>{

    }

    const handleSetAvatar = (event)=>{
        const file = event.target.files[0];
        const formData = new FormData();
        formData.append('file', file);
        console.log("哈哈哈：",file, formData);
        postUpload('/api/system/user/uploadImage', formData).then(res=>{
            console.log(res);
        });

        const reader = new FileReader(); //创建FileReader对象实例reader
        reader.readAsDataURL(file); //将图片url转换为base64码
        reader.onload = function(e){
            console.log(e.target.result);
            setPreviewAvatar(e.target.result);

            /*postAjax('/api/system/user/uploadAvatar', { file }).then(res=>{
                console.log(res);
            })*/

            systemUsersService.ApiUserUpdate({
                ...formik.values,
                avatarUrl: e.target.result
            }).then(res=>{
                console.log('hello',res)
            })
        };
        console.log(reader);
    }

    const handleSetText = (event)=>{
        const file = event.target.files[0];
        console.log(file);
        const reader = new FileReader(); //创建FileReader对象实例reader
        reader.readAsText(file, 'gb2312'); //将文本url转换为gb2312码
        reader.onload = function(e){
            console.log(e.target.result);
            setPreviewText(e.target.result)
        };
        console.log(reader);

    }

    const handleStringToHTML = (str) => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(str, 'text/html');
        return doc.body;
    };

    const handleParseExcel = (inputElement) => {
        const files = inputElement.target.files || [];
        if (!files.length) return;
        const file = files[0];

        console.time();
        const reader = new FileReader();
        reader.onloadend = function(event) {
            const arrayBuffer = reader.result;
            // debugger

            const options = { type: 'array' };
            const workbook = XLSX.read(arrayBuffer, options);
            console.timeEnd();

            const sheetName = workbook.SheetNames;
            const sheet = workbook.Sheets[sheetName];
            setPreviewExcel(XLSX.utils.sheet_to_html(sheet));
        };
        reader.readAsArrayBuffer(file);
    }


    useEffect(()=>{
        formik.setValues(state?.initialValues)
    }, [state?.initialValues])

    return (
        <Page title="User | Minimal-UI">
            <Container>
                <Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
                    <Typography variant="h4" gutterBottom>
                        User Profile
                    </Typography>
                </Stack>

                <form onSubmit={formik.handleSubmit}>
                    <Grid container spacing={3}>
                        <Grid item xs={12} sm={6} md={4}>
                            <Card sx={{ p: '1rem'}}>
                                <Scrollbar>
                                    <CardContent>
                                        <div>
                                            <div>
                                                excel
                                                <input onChange={handleParseExcel} accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" autoComplete="off" tabIndex="-1" />
                                            </div>
                                            <div>
                                                text
                                                <input onChange={handleSetText} accept="text/*" or-accept="text/plain" type="file" autoComplete="off" tabIndex="-1" />
                                            </div>
                                            <input  id="file" onChange={handleSetAvatar} accept="image/*" type="file" autoComplete="off" tabIndex="-1" style={{display: 'none'}} />
                                            <label for="file">
                                                <Avatar
                                                    alt={`avatar`}
                                                    src={previewAvatar || formik.values.avatarUrl || mockImgAvatar(24)}
                                                    sx={{
                                                        margin: 'auto',
                                                    }}
                                                />
                                            </label>
                                            <div>{previewText}</div>
                                            <div>{previewExcel}</div>
                                        </div>
                                    </CardContent>
                                </Scrollbar>
                            </Card>
                        </Grid>

                        <Grid item xs={12} sm={6} md={8}>
                            <Card>
                                <Scrollbar>
                                    <CardContent sx={{
                                        display: 'grid',
                                        gap: '24px 16px',
                                        gridTemplateColumns: 'repeat(2, 1fr)'
                                    }}>
                                        <FormControl fullWidth>
                                            <InputLabel htmlFor="profile-name-outlined">Name</InputLabel>
                                            <OutlinedInput
                                                id="profile-name-outlined"
                                                label="Name"
                                                name="name"
                                                value={formik.values.name}
                                                onChange={formik.handleChange}
                                            />
                                        </FormControl>

                                        <FormControl fullWidth>
                                            <InputLabel htmlFor="profile-email-outlined">Email Address</InputLabel>
                                            <OutlinedInput
                                                id="profile-email-outlined"
                                                label="Email Address"
                                                name="email"
                                                value={formik.values.email}
                                                onChange={formik.handleChange}
                                            />
                                        </FormControl>

                                        {/*<FormControl fullWidth>
                                            <InputLabel htmlFor="profile-mobile-phone-outlined">Mobile Phone</InputLabel>
                                            <OutlinedInput
                                                id="profile-mobile-phone-outlined"
                                                label="Mobile Phone"
                                                name="telephone"
                                                value={formik.values.telephone}
                                                onChange={formik.handleChange}
                                            />
                                        </FormControl>*/}

                                        {/*<FormControl fullWidth>
                                            <InputLabel htmlFor="profile-office-phone-outlined">Office Phone</InputLabel>
                                            <OutlinedInput
                                                id="profile-office-phone-outlined"
                                                label="Office Phone"
                                                name="phone"
                                                value={formik.values.phone}
                                                onChange={formik.handleChange}
                                            />
                                        </FormControl>*/}

                                        <FormControl fullWidth>
                                            <InputLabel id="profile-gender-outlined">Gender</InputLabel>
                                            <Select
                                                labelId="profile-gender-outlined"
                                                id="profile-gender"
                                                label="Gender"
                                                name="gender"
                                                value={formik.values.gender}
                                                onChange={formik.handleChange}
                                            >
                                                <MenuItem value={`0`}>男</MenuItem>
                                                <MenuItem value={`1`}>女</MenuItem>
                                                <MenuItem value={`2`}>保密</MenuItem>
                                            </Select>
                                        </FormControl>

                                        <LocalizationProvider dateAdapter={AdapterDateFns}>
                                            <DatePicker
                                                label="Dob"
                                                name="dob"
                                                value={formik.values.dob}
                                                onChange={(newValue) => {
                                                    formik.setFieldValue('dob', newValue)
                                                }}
                                                renderInput={(params) => <TextField fullWidth {...params} />}
                                            />
                                        </LocalizationProvider>

                                    </CardContent>
                                    <CardActions sx={{ p: 4 }}>
                                        <Button
                                            variant="contained"
                                            color="primary"
                                            type="submit"
                                        >
                                            Save Changes
                                        </Button>
                                    </CardActions>
                                </Scrollbar>
                            </Card>
                        </Grid>
                    </Grid>
                </form>
            </Container>
        </Page>
    );
}

const BuildDialog = ({}) => {


    const { state, dispatch } = useContext(ProfileContext);

    const formik = useFormik({
        initialValues: state.initialValues,
        onSubmit: (values, event) => {
            values.id ? putAjax(`/api/system/user`, values).then(data=>{
                console.log('hello',data)
            }) : postAjax(`/api/system/user`, values).then(data=>{
                console.log('world',data)
            })
        },
    });


    const handleFormSubmit = () => {
        formik.handleSubmit()
    }

    const handleClose = () => {
        dispatch({ type: 'OPEN_DIALOG', data: { title: '', open: false }});
    }

    return (
        <Dialog open={state.open} onClose={handleClose}  fullWidth aria-labelledby="task-dialog-title">
            <DialogTitle id="task-dialog-title">{state.title}</DialogTitle>
            <DialogContent className="py-3 w-full relative overflow-hidden">
                <form>
                    <TextField
                        id="task-code"
                        className="mb-4"
                        fullWidth
                        type="text"
                        size="small"
                        label="User Name"
                        name="name"
                        value={formik.values.name}
                        onChange={formik.handleChange}
                    />
                    <TextField
                        id="task-code"
                        className="mb-4"
                        fullWidth
                        type="text"
                        size="small"
                        label="Email"
                        name="email"
                        value={formik.values.email}
                        onChange={formik.handleChange}
                    />

                    <LocalizationProvider dateAdapter={AdapterDateFns}>
                        <DatePicker
                            label="Dob"
                            name="dob"
                            value={formik.values.dob}
                            onChange={(newValue) => {
                                formik.setFieldValue('dob', newValue)
                            }}
                            renderInput={(params) => <TextField size="small" fullWidth {...params} />}
                        />
                    </LocalizationProvider>

                </form>
            </DialogContent>
            <DialogActions>
                <Button onClick={handleClose}>取消</Button>
                <Button onClick={handleFormSubmit} autoFocus>
                    提交
                </Button>
            </DialogActions>
        </Dialog>
    );
}

const Profile = () => {

    const { userId } = useParams();

    const [state, dispatch] = useReducer(reducer, { initialValues });

    const [detail, setDetail] = useState({});

    const queryUserProfile = ()=>{
        systemUsersService.ApiUserInfo({ userId }).then(res=>{
            setDetail(res);
            dispatch({
                type: 'EDIT_FORM',
                data: { initialValues: res }
            })
        });
    }

    useEffect(() => {
        queryUserProfile()
    }, []);

    return (
        <ProfileContext.Provider value={{ state, dispatch }}>
            <EnhancedDetail detail={detail} />
            {
                state.open &&
                <BuildDialog />
            }
        </ProfileContext.Provider>
    );
}

export default Profile;